package cn.cqautotest.cqviehelper.utils.network;

import com.blankj.utilcode.util.GsonUtils;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;

public class MyOkHttp {
    private static final String TAG = MyOkHttp.class.getSimpleName();
    public static final HttpLoggingInterceptor logger = new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT);

    static {
        logger.level(HttpLoggingInterceptor.Level.BODY);
    }

    private static final OkHttpClient client = new OkHttpClient().newBuilder()
            .addInterceptor(logger)
            .build();

    public static FormBody.Builder getFormBody() {
        return new FormBody.Builder();
    }

    public static <T> T postData(String url, FormBody.Builder builder, Headers headers, Class<T> tClazz) throws Exception {
        String result = postData(url, builder, headers);
        return GsonUtils.fromJson(result, tClazz);
    }

    public static String postData(String url, FormBody.Builder builder, Headers headers) throws Exception {
        Request.Builder requestBuilder = new Request.Builder()
                .url(url);
        if (builder != null) {
            requestBuilder.post(builder.build());
        } else {
            requestBuilder.get();
        }
        if (headers != null) {
            requestBuilder.headers(headers);
        }
        Request request = requestBuilder.build();
        Response response = client.newCall(request).execute();
        ResponseBody responseBody = response.body();
        String result = "";
        if (responseBody != null) result = responseBody.string();
        // if (ObjectUtils.isNotEmpty(headers)) {
        //    Log.d(TAG, "postData: =======> headers info is " + headers.toString());
        // }
        // Log.d(TAG, "postData: =======> response is " + response);
        // Log.d(TAG, "postData: =======> result is " + result);
        return result;
    }
}
